<template>
  <div class="login-container">
    <!-- 下面使用element的卡片，做中间的那个盒子 -->
    <el-card shadow="hover">
      <div class="login-title"></div>
      <el-form ref="form" :model="login" :rules="rules">
        <el-form-item prop="username">
          <el-input placeholder="请输入用户名" v-model="login.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            placeholder="请输入密码"
            v-model="login.password"
            show-password
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="user">登录</el-button>
        </el-form-item>
      </el-form>
      <el-link :underline="false" @click="$router.push('/reg')">去注册</el-link>
    </el-card>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'MyLoging',
  data() {
    return {
      login: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    user() {
      // 当点击登录的时候，先进行完整的验证，验证不通过就return，验证通过则提交数据
      // 表单.validator(valid => { valid===true |  valid===false })
      this.$refs.form.validate(async valid => {
        if (!valid) return // 验证不通过，return
        console.log('验证通过，要提交的数据是：', this.login)
        const { data: res } = await loginAPI(this.login)
        // console.log(res)
        if (res.code === 0) {
          // 成功：提示、存token、跳转到首页
          this.$message.success(res.message)
          // ????? 存储token
          this.$store.commit('user/updateToken', res.token)
          // 跳转 ？？？？
          this.$router.push('/home')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.login-container {
  height: 100%;
  background: url(@/assets/images/login_bg.jpg) no-repeat;
  background-size: cover;
}
.el-card {
  // height: 300px; // 高度随便加一个，最后完成后，去掉，让高度自动撑开
  width: 400px;
  position: absolute;
  left: 50%; // 针对父级元素的50%
  top: 50%;
  transform: translate(-50%, -50%); // 向回平移自身的50%
  .login-title {
    height: 40px;
    background: url(@/assets/images/login_title.png) 50% no-repeat;
  }
}
.el-button {
  width: 100%;
}
</style>
